Imports System.Collections
Imports System.Windows.Forms

Namespace xpComponent.Form
    Public Class ListViewItemSorter
        Implements IComparer

        Public COUNT As Integer = 0
        Public INDEX As Integer = 1

        Public Sub New()
            MyBase.new()
        End Sub

        Public Sub New(ByVal ColumnIndex As Integer)
            Me.INDEX = ColumnIndex
        End Sub

        Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare
            Dim Item1 As ListViewItem = CType(x, ListViewItem)
            Dim Item2 As ListViewItem = CType(y, ListViewItem)
            If Item1.SubItems(INDEX).Text > Item2.SubItems(INDEX).Text Then
                Return 1
            Else
                If Item1.SubItems(INDEX).Text < Item2.SubItems(INDEX).Text Then
                    Return -1
                Else
                    Return 0
                End If
            End If
        End Function
    End Class

    Public Class ListViewColumnSorter
        Implements System.Collections.IComparer

        Private ColumnToSort As Integer
        Private OrderOfSort As SortOrder
        Private ObjectCompare As CaseInsensitiveComparer

        Public Sub New()
            ColumnToSort = 0
            OrderOfSort = SortOrder.None
            ObjectCompare = New CaseInsensitiveComparer
        End Sub

        Public Sub New(ByVal column As Integer)
            ColumnToSort = column
            OrderOfSort = SortOrder.None
            ObjectCompare = New CaseInsensitiveComparer
        End Sub

        Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements IComparer.Compare
            Dim compareResult As Integer
            Dim listviewX As ListViewItem
            Dim listviewY As ListViewItem

            listviewX = CType(x, ListViewItem)
            listviewY = CType(y, ListViewItem)

            compareResult = ObjectCompare.Compare(listviewX.SubItems(ColumnToSort).Text, listviewY.SubItems(ColumnToSort).Text)

            If (OrderOfSort = SortOrder.Ascending) Then
                Return compareResult
            ElseIf (OrderOfSort = SortOrder.Descending) Then
                Return (-compareResult)
            Else
                Return 0
            End If
        End Function

        Public Property SortColumn() As Integer
            Set(ByVal Value As Integer)
                ColumnToSort = Value
            End Set
            Get
                Return ColumnToSort
            End Get
        End Property

        Public Property Order() As SortOrder
            Set(ByVal Value As SortOrder)
                OrderOfSort = Value
            End Set
            Get
                Return OrderOfSort
            End Get
        End Property
    End Class
End Namespace